package com.wtx.chapter03.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @description:
 * @author: wtx
 * @createDate: 2020/5/29
 */
public class MyChatServerHandler extends SimpleChannelInboundHandler<String> {

    // 保存与服务端连接的channel
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    protected void channelRead0(ChannelHandlerContext ctx, final String s) throws Exception {

        final Channel own = ctx.channel();

        //java8 的遍历
        channelGroup.forEach( channel -> {
            if (channel==own)
                channel.writeAndFlush("我: "+s+"\n");
            else
                channel.writeAndFlush(channel.remoteAddress()+ ": "+s+"\n");
        });
    }

    //某个客户端与服务端建立了连接
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();

        //在添加这个channel之前广播
        // ChannelGroup会遍历所有的channel
        channelGroup.writeAndFlush("[服务器提示]--"+ channel.remoteAddress() +" 加入聊天室");

        channelGroup.add(channel);
    }

    //某个channel断开
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[服务器提示]--"+channel.remoteAddress()+" 离开聊天室");

        //channelGroup.remove(channel); netty会自动调用
    }

    //channel 被激活
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress()+ " 上线");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress()+ " 下线");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
